<!--
 * @描述: 用户管理
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" :placeholder="$t('sysuser.username')" clearable class="filter-input filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.status" :placeholder="$t('sysuser.status')" clearable class="filter-input filter-item">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves type="primary" class="filter-item" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.query') }}
      </el-button>
      <el-button v-waves type="primary" class="filter-item" icon="el-icon-refresh-right" @click="handleReset">
        {{ $t('common.reset') }}
      </el-button>
      <el-button type="primary" class="filter-item" icon="el-icon-plus" @click="handleCreate">
        {{ $t('common.add') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" type="primary" class="filter-item" @click="handleDownload">
        <svg-icon icon-class="excel" style="margin-right: 5px" />
        {{ $t('common.export') }}
      </el-button>
      <el-button type="primary" class="filter-item" icon="el-icon-postcard" @click="handleAuthorizeRole">
        {{ $t('sysuser.grant-role') }}
      </el-button>
      <el-button type="danger" plain class="filter-item" icon="el-icon-delete" @click="handleDelete">
        {{ $t('common.delete') }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      :row-style="{height:'30px'}"
      :cell-style="{padding:'0px'}"
      :header-cell-style="{padding:'0px'}"
      style="width: 100%"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column :label="$t('sysuser.username')" prop="username" />
      <el-table-column :label="$t('sysuser.nickname')" prop="nickname" />
      <el-table-column :label="$t('sysuser.mobile')" prop="mobile" />
      <el-table-column :label="$t('sysuser.roleId')" prop="roleIdCn" />
      <el-table-column :label="$t('sysuser.orgId')" prop="orgIdCn" />
      <el-table-column :label="$t('common.create-time')" min-width="110px" prop="createTime" sortable="custom" :class-name="getSortClass('createTime')">
        <template slot-scope="{row}">
          <span>{{ row.createTime | formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('sysuser.status')" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            <span v-if="row.status === 1">{{ $t('common.able') }}</span>
            <span v-else>{{ $t('common.disable') }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operate')" align="center">
        <template slot-scope="{row,$index}">
          <el-button type="text" @click="handleUpdate(row)">
            <i class="el-icon-edit-outline" />{{ $t('common.edit') }}
          </el-button>
          <el-popover :ref="'popover-' + row.id" placement="top" width="160" :title="$t('common.confirm-delete')" trigger="click">
            <div>
              <el-button size="mini" @click="$refs[`popover-` + row.id].doClose()">{{ $t('common.cancel') }}</el-button>
              <el-button type="primary" size="mini" @click="$refs[`popover-` + row.id].doClose();handleDelete(row,$index)">{{ $t('common.confirm') }}</el-button>
            </div>
            <el-button slot="reference" type="text" style="margin-left: 10px">
              <i class="el-icon-delete" />{{ $t('common.delete') }}
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-tabs v-model="activeName" style="width: 100%" type="border-card">
      <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key">
        <keep-alive>
          <sysuserpost v-if="activeName==item.key" :msg="parentMsg" :type="item.key" />
        </keep-alive>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" :label-position="labelPosition" label-width="90px" style="width: 100%">
        <el-form-item :label="$t('sysuser.username')" prop="username">
          <el-input v-model="temp.username" :placeholder="$t('common.enter')" :disabled="dialogStatus==='update'" minlength="3" maxlength="64" clearable />
        </el-form-item>
        <el-form-item v-if="dialogStatus==='create'" :label="$t('sysuser.password')" prop="password">
          <el-input v-model="temp.password" :placeholder="$t('common.enter')" show-password minlength="6" maxlength="31" clearable />
        </el-form-item>
        <el-form-item :label="$t('sysuser.email')" prop="email">
          <el-input v-model="temp.email" :placeholder="$t('common.enter')" maxlength="100" clearable />
        </el-form-item>
        <el-form-item :label="$t('sysuser.mobile')">
          <el-row>
            <el-col :span="4" :xs="24">
              <el-select v-model="temp.prefix" :placeholder="$t('common.choose')">
                <el-option label="+86" value="86" />
                <el-option label="+87" value="87" />
              </el-select>
            </el-col>
            <el-col :span="20" :xs="24">
              <el-form-item prop="mobile">
                <el-input v-model="temp.mobile" :placeholder="$t('common.enter')" class="input-with-select" maxlength="20" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item :label="$t('sysuser.orgId')" prop="orgId">
          <el-select ref="selectOrgId" v-model="temp.orgId" :placeholder="$t('common.choose')" style="width: 100%" clearable @clear="handleClearOrgId">
            <el-option :key="temp.orgId" hidden :value="temp.orgId" :label="orgName" />
            <el-tree :data="orgIdOptions" :props="{label: 'title'}" :expand-on-click-node="false" :check-on-click-node="true" @node-click="handleNodeClickOrgId" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('sysuser.status')" prop="status">
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">{{ $t('common.able') }}</el-radio>
            <el-radio :label="0">{{ $t('common.disable') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" :disabled="disabledStatus" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog v-el-drag-dialog :title="$t('sysuser.grant-role')" :visible.sync="authorizeRoleDialogFormVisible" width="630px">
      <el-select v-model="temp.postCode" :placeholder="$t('syspost.choose-post')" style="width: 95%" clearable @change="handleNodeClickParentId">
        <el-option v-for="item in postCodeOptions" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <br>
      <br>
      <el-transfer v-model="grantRoleList" :data="roleList" filterable :props="{label: 'name', key: 'value'}" :filter-placeholder="$t('sysuser.filter-roleName')" :titles="[$t('sysuser.unauthorized-role'), $t('sysuser.authorized-role')]" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="authorizeRoleDialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="createAuthorizeRoleButton()">
          {{ $t('common.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { querySysUser, querySysUserPostTree, addSysUser, updateSysUser, queryRoleName, querySysOrgTree, deleteSysUser, exportSysUser, authorizeRoleToUser } from '@/api/admin'
import waves from '@/directive/waves' // waves directive
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import sysuserpost from './components/sysuserpost'
import qs from 'qs'
import { saveAs } from 'file-saver'
import Sortable from 'sortablejs'

export default {
  name: 'SysUser',
  components: { Pagination, sysuserpost },
  directives: { waves, elDragDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tabMapOptions: [
        { label: this.$t('sysuserpost.postInfo'), key: 'sysuserpost' }
      ],
      activeName: 'sysuserpost',
      parentMsg: [],
      tableKey: 0,
      labelPosition: 'right',
      list: [],
      total: 0,
      listLoading: true,
      disabledStatus: false,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        username: undefined,
        status: undefined,
        sorter: 'createTime_descend'
      },
      roleList: [],
      grantRoleList: [],
      orgIdOptions: [],
      postCodeOptions: [],
      orgName: '',
      statusOptions: [
        { key: '1', display_name: this.$t('common.able') },
        { key: '0', display_name: this.$t('common.disable') }
      ],
      temp: {
        id: undefined,
        status: 1,
        prefix: '86'
      },
      multipleSelection: [],
      dialogFormVisible: false,
      authorizeRoleDialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: this.$t('common.edit'),
        create: this.$t('common.add')
      },
      rules: {
        username: [{ required: true, validator: this.checkUsername, trigger: ['blur', 'change'] }],
        password: [{ required: true, validator: this.checkPassword, trigger: ['blur', 'change'] }],
        email: [{ required: true, type: 'email', validator: this.checkEmail, trigger: ['blur', 'change'] }],
        mobile: [{ required: true, validator: this.checkMobile, trigger: ['blur', 'change'] }],
        orgId: [{ required: true, validator: this.checkOrgId, trigger: 'change' }],
        status: [{ required: true }]
      },
      downloadLoading: false
    }
  },
  created() {
    if (window.innerWidth < 700) {
      this.labelPosition = 'top'
    }
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      querySysUser(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.pagination.total
        this.listLoading = false
        this.$nextTick(() => {
          if (this.list && this.list.length > 0) {
            this.$refs.multipleTable.toggleRowSelection(this.list[this.list.length - 1], true)
          }
        })
      })
      querySysOrgTree().then(response => {
        this.orgIdOptions = response.data.list
      })
      this.$nextTick(() => {
        this.setSort()
      })
    },
    setSort() {
      const el = this.$refs.multipleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
        }
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    handleReset() {
      this.listQuery.username = ''
      this.listQuery.status = ''
      this.handleFilter()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'createTime') {
        this.sortByCreateTime(order)
      }
    },
    sortByCreateTime(order) {
      if (order === 'ascending') {
        this.listQuery.sorter = 'createTime_ascend'
      } else {
        this.listQuery.sorter = 'createTime_descend'
      }
      this.handleFilter()
    },
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val.pop())
      } else {
        this.multipleSelection = val
        this.parentMsg = val
      }
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        status: 1,
        prefix: '86'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.orgName = ''
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      if (this.$refs.selectOrgId.value) {
        this.validateOrgId()
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.disabledStatus = true
          addSysUser(this.temp).then(response => {
            if (response.message === 'success') {
              this.list.unshift(this.temp)
              this.disabledStatus = false
              this.dialogFormVisible = false
              this.$message({
                message: this.$t('common.add-success'),
                type: 'success',
                duration: 2000
              })
              this.handleReset()
            } else {
              this.handleWarning(response)
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      if (row.roleId) {
        this.temp.roleId = row.roleId.split(',')
      }
      this.orgName = this.temp.orgIdCn
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (this.$refs.selectOrgId.value) {
        this.validateOrgId()
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // const tempData = Object.assign({}, this.temp)
          const tempData = {}
          tempData.id = this.temp.id
          tempData.username = this.temp.username
          tempData.email = this.temp.email
          tempData.mobile = this.temp.mobile
          tempData.prefix = this.temp.prefix
          tempData.roleId = this.temp.roleId
          tempData.orgId = this.temp.orgId
          tempData.status = this.temp.status
          this.disabledStatus = true
          updateSysUser(tempData).then(response => {
            if (response.message === 'success') {
              this.disabledStatus = false
              this.dialogFormVisible = false
              this.$message({
                message: this.$t('common.edit-success'),
                type: 'success',
                duration: 2000
              })
              this.handleReset()
            } else {
              this.handleWarning(response)
            }
          })
        }
      })
    },
    handleAuthorizeRole() {
      if (this.multipleSelection.length === 0) {
        this.handleWarning(this.$t('sysuser.check-user'))
        return
      }
      if (this.multipleSelection.length > 1) {
        this.handleWarning(this.$t('common.check-one'))
        return
      }
      this.temp.postCode = this.multipleSelection[0].postCode
      queryRoleName().then(response => {
        this.roleList = response.data
        queryRoleName(this.multipleSelection[0].id, this.temp.postCode, 1).then(assignResponse => {
          const assignData = []
          assignResponse.data.map(item => { assignData.push(item.value) })
          this.grantRoleList = assignData
          querySysUserPostTree(this.multipleSelection[0].id).then(sysUserPostResponse => {
            this.postCodeOptions = sysUserPostResponse.data
            this.authorizeRoleDialogFormVisible = true
          })
        })
      })
    },
    createAuthorizeRoleButton() {
      if (!this.temp.postCode) {
        this.handleWarning(this.$t('syspost.choosepost-required'))
        return
      }
      if (this.grantRoleList.length === 0) {
        this.handleWarning(this.$t('sysuser.role-required'))
        return
      }

      const tempData = {}
      tempData.userId = this.multipleSelection[0].id
      tempData.roleId = this.grantRoleList
      tempData.postCode = this.temp.postCode
      authorizeRoleToUser(tempData).then(response => {
        if (response.message === 'success') {
          this.authorizeRoleDialogFormVisible = false
          this.$message({
            message: this.$t('sysuser.grant-role') + this.$t('common.success'),
            type: 'success',
            duration: 2000
          })
          this.handleReset()
        } else {
          this.handleWarning(response)
        }
      })
    },
    handleDelete(row, index) {
      if (row.id) {
        this.delete(row.id)
      } else {
        if (this.multipleSelection.length === 0) {
          this.handleWarning(this.$t('common.choose-delete'))
          return
        }
        this.$confirm(this.$t('common.confirm-batch-delete'), this.$t('common.batch-delete'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.delete(this.multipleSelection.map(item => { return item.id }).join(','))
        }).catch(() => {})
      }
    },
    delete(deleteArray) {
      deleteSysUser(deleteArray).then(response => {
        if (response.message === 'success') {
          this.$message({
            message: this.$t('common.delete-success'),
            type: 'success',
            duration: 2000
          })
          this.handleReset()
        } else {
          this.handleWarning(response)
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      const listQueryData = {}
      listQueryData.username = this.listQuery.username
      listQueryData.status = this.listQuery.status
      exportSysUser(qs.stringify(listQueryData)).then(response => {
        saveAs(response, this.$t('route.sysuser') + '.xlsx')
      })
      this.downloadLoading = false
    },
    getSortClass: function(key) {
      const sorter = this.listQuery.sorter
      return sorter === `${key}_ascend` ? 'ascending' : 'descending'
    },
    handleWarning(response) {
      this.$message({
        message: response.message || response,
        type: 'warning',
        duration: 2000
      })
      this.disabledStatus = false
    },
    checkUsername(rule, value, callback) {
      if (!value) {
        return callback(new Error(this.$t('sysuser.username-required')))
      } else {
        if (value.length > 2 && value.length < 65) {
          callback()
        } else {
          return callback(new Error(this.$t('sysuser.username-length')))
        }
      }
    },
    checkPassword(rule, value, callback) {
      if (!value) {
        return callback(new Error(this.$t('sysuser.password-required')))
      } else {
        if (value.length > 5 && value.length < 32) {
          callback()
        } else {
          return callback(new Error(this.$t('sysuser.password-length')))
        }
      }
    },
    checkEmail(rule, value, callback) {
      if (!value) {
        return callback(new Error(this.$t('sysuser.email-required')))
      } else {
        const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error(this.$t('sysuser.email-format')))
        }
      }
    },
    checkMobile(rule, value, callback) {
      if (!value) {
        return callback(new Error(this.$t('sysuser.mobile-required')))
      } else {
        const reg = /^1\d{10}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error(this.$t('sysuser.mobile-format')))
        }
      }
    },
    checkOrgId(rule, value, callback) {
      if (!value) {
        return callback(new Error(this.$t('sysuser.orgId-required')))
      } else {
        callback()
      }
    },
    validateOrgId() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate('orgId')
      })
    },
    handleNodeClickOrgId(data) {
      this.orgName = data.title
      this.temp.orgId = data.id
      this.$refs.selectOrgId.blur()
      this.validateOrgId()
    },
    handleClearOrgId() {
      this.orgName = ''
      this.temp.orgId = ''
    },
    handleNodeClickParentId(data) {
      queryRoleName(this.multipleSelection[0].id, data, 1).then(assignResponse => {
        const assignData = []
        assignResponse.data.map(item => { assignData.push(item.value) })
        this.grantRoleList = assignData
      })
    }
  }
}
</script>
<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
</style>
<style scoped>
  .pagination-container {
    padding: 10px;
    margin: 0px;
  }
</style>
